package com.itheima.tliasmanagement.aop;

import com.itheima.tliasmanagement.dto.LoginDto;
import com.itheima.tliasmanagement.entity.EmpLoginLog;
import com.itheima.tliasmanagement.mapper.EmpLoginLogMapper;
import com.itheima.tliasmanagement.vo.LoginResultVo;
import com.itheima.tliasmanagement.vo.Result2;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class LoginLogAspect {

    @Autowired
    private EmpLoginLogMapper empLoginLogMapper;

    @Around("execution(* com.itheima.tliasmanagement.controller.LoginController.login(..))")
    public Object recordLoginLog(ProceedingJoinPoint pjp) throws Throwable{

        // 获取用户名和密码
        Object[] args = pjp.getArgs();
        String username = "";
        String password = "";
        for (Object arg : args) {
            if (arg instanceof LoginDto) {
                LoginDto dto = (LoginDto) arg;
                username = dto.getUsername();
                password = dto.getPassword();
                break;
            }
        }
        long begin = System.currentTimeMillis();

        // 调用原始方法
        Object obj = null;
        try {
            obj = pjp.proceed();
        } finally {
            long end = System.currentTimeMillis();

            // 获取登录结果和JWT信息
            Short isSuccess = 0;
            String jwt = "";
            if (obj instanceof Result2) {
                Result2 result2 = (Result2) obj;
                isSuccess = result2.getCode().shortValue();
                if (isSuccess == 1) { // 登录成功
                    Object data = result2.getData();
                    if (data instanceof LoginResultVo) {
                        LoginResultVo loginVo = (LoginResultVo) data;
                        jwt = loginVo.getToken();
                    }
                }
            }

            // 记录登录日志
            EmpLoginLog loginLog = new EmpLoginLog(null, username, password, LocalDateTime.now(), isSuccess, jwt, end - begin);
            empLoginLogMapper.insertLoginLog(loginLog);
        }

        return obj;
    }

}
